package com.coin900.coin.cmd.user;

import com.coin900.coin.base.Constants;
import com.google.gson.Gson;
import com.coin900.coin.base.FuConstants;
import com.coin900.coin.base.utils.JwtUtils;
import com.coin900.coin.cmd.ACmd;
import com.coin900.coin.cmd.CmdSign;
import com.coin900.coin.code.CmdCode;
import com.coin900.coin.persist.fu.FuUserVO;
import com.coin900.coin.service.IQiniuService;
import com.coin900.coin.service.fu.IFuUserService;
import com.value.exception.BusinessException;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shui
 * @create 2017-12-11
 **/
@Controller
public class SessionGetCmd extends ACmd {

    @Override
    public CmdSign execute(HttpServletRequest request, CmdSign sign) throws Exception {
        CmdSign respSign = new CmdSign(sign);
        String sessionToken = sign.getSessionToken();
        Claims claims = JwtUtils.checkJWT(sessionToken, Constants.jwt_base64Security);
        Long userId = Long.parseLong(claims.get("userId").toString());
        Map<String, Object> params = new HashMap<>();
        params.put("id", userId);
        List<FuUserVO> userVOList = userService.loadFuUser(params);
        if (userVOList.isEmpty()) {
            throw new BusinessException("用户未登录");
        }
        FuUserVO fuUserVO = userVOList.get(0);
        String upToken = qiniuService.getUpToken();
        fuUserVO.setUpToken(upToken);
        fuUserVO.setBucketDomain(FuConstants.BUCKET_DOMAIN);

        String source = new Gson().toJson(fuUserVO);
        respSign.setSource(source);
        return respSign;
    }

    @Override
    public String getCmdCode() {
        return CmdCode.SESSION_GET;
    }

    @Autowired
    IFuUserService userService;
    @Autowired
    IQiniuService qiniuService;


}
